<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width,initial-scale=1">
		<meta name="divport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0" />
		<title>个体户认证</title>
		<link rel="stylesheet" href="css/individualAuth.css" type="text/css" />
	</head>
	<body>
		<div class="forms" id="app">
			<form v-if="auth_status == null || auth_status == ''">
				<div class="group-card">
					<div class="forms-item forms-item-border hide-border forms-item-error">
						<div class="forms-item-inner">
							<div class="forms-item-label">
								<span class="label-text">真实姓名</span>
							</div>
							<div class="forms-item-content">
								<div class="input-wrap">
									<input v-model="formInline.real_name" type="text" class="hide-border input-content"
										name="real_name" id="real_name" placeholder="请输入姓名"
										@focus="cancelError('real_name')" />
								</div>
							</div>
						</div>
						<div class="error-message error-msg--boeder" style="padding-left: 10px">
							<span class="error-message-text">{{errorMsg.real_name}}</span>
						</div>
					</div>
					<div class="forms-item forms-item-border forms-item-error">
						<div class="forms-item-inner">
							<div class="forms-item-label">
								<span class="label-text">身份证号</span>
							</div>
							<div class="forms-item-content">
								<div class="input-wrap">
									<input v-model="formInline.id_card" type="text" class="hide-border input-content"
										name="id_card" id="id_card" placeholder="请输入身份证号"
										@focus="cancelError('id_card')">
								</div>
							</div>
						</div>
						<div class="error-message error-msg--boeder" style="padding-left: 10px">
							<span class="error-message-text">{{errorMsg.id_card}}</span>
						</div>
					</div>
          <div class="forms-item forms-item-border forms-item-error">
            <div class="forms-item-inner is-direction-top">
              <div class="forms-item-label" style="width: 120px;">
                <span class="label-text">身份证人像面</span>
              </div>
              <div class="input-wrap upload-file">
                <input type="file" accept="image/*" class="upload-input" name="img_front"
                       v-on:change="change($event,'frontSrc')" @focus="cancelError('img_front')">
                <img :src="frontSrc" class="upload-icon"
                     :style="{height:frontSrc == './images/img_front.svg' ? '160px' : 'auto'}" />
              </div>
            </div>
            <div class="error-message error-msg--boeder" style="padding-left: 10px">
              <span class="error-message-text">{{errorMsg.img_front}}</span>
            </div>
          </div>
          <div class="forms-item forms-item-border forms-item-error">
            <div class="forms-item-inner is-direction-top">
              <div class="forms-item-label" style="width: 120px;">
                <span class="label-text">身份证国徽面</span>
              </div>
              <div class="input-wrap upload-file">
                <input type="file" accept="image/*" class="upload-input" name="img_reverse" id="img_reverse"
                       v-on:change="change($event,'reverseSrc')" @focus="cancelError('img_reverse')">
                <img :src="reverseSrc" class="upload-icon"
                     :style="{height:reverseSrc == './images/img_reverse.svg' ? '160px' : 'auto'}" />
              </div>
            </div>
            <div class="error-message error-msg--boeder" style="padding-left: 10px">
              <span class="error-message-text">{{errorMsg.img_reverse}}</span>
            </div>
          </div>
				</div>
				<div class="form-submit">
					<div class="submit-btn" :style="{backgroundColor: disable ? '#c0c0c0' : '#0073B1'}" @click="submit">
						<span v-if="disable" class="loading-flower" style="margin-right: 4px;"></span>
						<span>申请认证</span>
					</div>
				</div>
			</form>
			<!-- 审核中展示内容 -->
			<div v-if="auth_status == 1 || auth_status == 3">
				<div class="submit-success">
					<img src="./images/submit_success.svg" />
					<span style="font-weight: bold;font-size: 20px;line-height: 40px;">审核中</span>
					<span style="line-height: 30px;color: rgb(150, 150, 150)">审核通过后，我们会第一时间通过站内信息告知您！</span>
					<span style="line-height: 30px;color: #0073B1" @click="editInfo">修改申请信息</span>
				</div>
			</div>
			<!-- modal弹窗 -->
			<div v-if="showModal" class="modal" style="display: none;" :style="{display:showModal?'flex':'none'}"
				hover-stop-propagation @touchmove.stop.prevent="() => {}">
				<!-- 弹窗内容 -->
				<div class="modal-content">
					<div class="modal-body">
						<span class="loading-flower" style="width: 40px;height: 40px;"></span>
					</div>
					<div class="modal-footer">
						<h3>加载中...</h3>
					</div>
				</div>
			</div>
			<!-- toast弹窗 -->
			<div v-if="showToast" class="modal" style="display: none;background-color: unset;"
				:style="{display:showToast?'flex':'none'}">
				<!-- 弹窗内容 -->
				<div class="modal-content" style="padding: 10px;">
					<div class="modal-body">
						<span style="color: #fff;">{{toastMsg}}</span>
					</div>
				</div>
			</div>

		</div>
	</body>

	<!-- vue 的 SDK -->
	<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
	<!-- jquery 的 SDK -->
	<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>

	<script>
		new Vue({
			el: '#app',
			data: {
				type: 1, //1添加 2编辑
				accessToken: '',
				auth_status: null, //1待认证 2已认证 3未通过
				formInline: { //表单字段数据
					real_name: '',
					id_card: '',
					img_reverse: '',
					img_front: ''
				},
				reverseSrc: './images/img_reverse.svg', //国徽
				frontSrc: './images/img_front.svg', //人像
				disable: false,
				showModal: false,
				showToast: false,
				toastMsg: '请输入身份证',
				errorMsg: { //表单字段错误信息
					real_name: '',
					id_card: '',
					img_reverse: '',
					img_front: ''
				}
			},
			created() {
				// 获取上一页面携带的参数
				let url = window.location.href;
				let p = url.split('?')[1];
				let params = new URLSearchParams(p);
				this.type = params.get('type');
				this.accessToken = params.get('accessToken');
				this.getAuthInfo();
			},
			methods: {
				// 获取认证信息
				getAuthInfo() {
          return new Promise(async (resolve) => {
            let url = 'https://xcxapi.xinsuofa.com/api/v1.0/individual/queryById';
            let token = this.accessToken;
            let authData = {},errMsg = '';
            $.ajax({
              async: false,
              url: url,
              type: "GET",
              contentType: false,
              processData: false,
              crossDomain: true == !(document.all),
              headers: {
                'accessToken': token
              },
              dataType: "json",
              success: function({
                  code,
                  msg,
                  data
                }) {
                switch (code) {
                  case 200:
                    authData = data;
                    errMsg = false;
                    break;
                  case 201:
                    errMsg = false;
                    break;
                  default:
                    errMsg = msg;
                }
              },
              error: function(response, err) {
                errMsg = response.responseText;
              }
            });
            if (errMsg) {
              this.waitingToast(errMsg);
            } else if(!errMsg && this.type == 2){
              this.auth_status = authData.auth_status || "";
              this.formInline.id_card = authData.id_card;
              this.formInline.real_name = authData.real_name;
                this.formInline.img_reverse = this.jointImg(authData.img_reverse);
                this.formInline.img_front = this.jointImg(authData.img_front);
              this.reverseSrc = this.jointImg(authData.img_reverse);
              this.frontSrc = this.jointImg(authData.img_front);
            }
            resolve();
          });
				},

				//验证参数（提交时）
				validateParams(params) {
					return new Promise((resolve) => {
						let noError = true;
						let regExps = {
							id_card: /(^\d{15}$)|(^\d{17}([0-9]|X)$)/
						};
						if (params.real_name === null || params.real_name === "") {
							this.errorMsg.real_name = '请输入姓名';
							noError = false;
						}
						if (params.id_card === null || params.id_card === "") {
							this.errorMsg.id_card = '请输入身份证号';
							noError = false;
						} else if (!(regExps.id_card.test(params.id_card))) {
							this.errorMsg.id_card = '请输入合法的身份证号';
							noError = false;
						}
						if (params.img_reverse === null || params.img_reverse === "") {
							this.errorMsg.img_reverse = '请上传身份证国徽面';
							noError = false;
						}
						if (params.img_reverse.size > 3145728) {
							this.errorMsg.img_reverse = '图片大小不能超过3MB';
							noError = false;
						}
						if (params.img_front === null || params.img_front === "") {
							this.errorMsg.img_front = '请上传身份证人像面';
							noError = false;
						}
						if (params.img_front.size > 3145728) {
							this.errorMsg.img_front = '图片大小不能超过3MB';
							noError = false;
						}
						resolve(noError);
					});
				},

				// 获取焦点后取消表单字段报错
				cancelError(field) {
					this.errorMsg[field] ? this.errorMsg[field] = '' : '';
				},

				//选择文件
				change(e, field) {
					let files = e.target.files || e.dataTransfer.files;
					// 获取 window 的 URL 工具
					let URL = window.URL || window.webkitURL;
					// 生成目标 url
          this[field] = URL.createObjectURL(files[0]);
					switch (field) {
						case 'reverseSrc':
							this.formInline.img_reverse = files[0];
							this.errorMsg['img_reverse'] ? this.errorMsg['img_reverse'] = '' : '';
							break;
						case 'frontSrc':
							this.formInline.img_front = files[0];
							this.errorMsg['img_front'] ? this.errorMsg['img_front'] = '' : '';
							break;
					}
				},

				// 提交表单
				async submit() {
					if (this.disable) return;
					this.disable = true;
					this.showModal = true;
					let params = this.formInline;
					let validateResult = await this.validateParams(params);
					if (!validateResult) {
						this.disable = false;
						this.showModal = false;
						return;
					}
					let url = this.type == 2 ? 'https://xcxapi.xinsuofa.com/api/v1.0/individual/edit' : 'https://xcxapi.xinsuofa.com/api/v1.0/individual/add'
					let token = this.accessToken;
					if (!Object.prototype.toString.call(params.img_reverse) === '[object Object]') {
						delete params.img_reverse;
					}
					if (!Object.prototype.toString.call(params.img_front) === '[object Object]') {
						delete params.img_front;
					}
					// 创建表单对象
					const formData = new FormData();
					for (key in params) {
						formData.append(key, params[key]);
					}
					let auth_status = this.auth_status,toastMsg = this.toastMsg;
					$.ajax({
						async: false,
						url: url,
						type: "POST",
						data: formData,
						contentType: false,
						processData: false,
						crossDomain: true == !(document.all),
						headers: {
							'accessToken': token
						},
						dataType: "json",
						success: function(data) {
							auth_status = 1;
							toastMsg = data.msg;
						},
						error: function(response, err) {
							toastMsg = response.responseText;
						}
					});
					this.showModal = false;
					this.disable = false;
					this.auth_status = auth_status;
					this.waitingToast(toastMsg);
				},

				// 编辑信息
        async editInfo() {
					this.type = 2;
					await this.getAuthInfo();
          this.auth_status = null;
        },

				// 定时展示toastMsg
				waitingToast(toastMsg) {
					this.toastMsg = toastMsg;
					this.showToast = true;
					setTimeout(() => {
						this.showToast = false;
					}, 2000);
				},
				// 处理图片
				jointImg(imgUrl) {
          if(imgUrl){
            var reg = /\"/g
            imgUrl = imgUrl.replace(reg,"");
            return imgUrl.indexOf('http') == 0 ? imgUrl : 'http://photo.xinsuofa.com' + imgUrl;
          }
				}
			}
		});
	</script>
</html>